package com.study.s01.array;

public class MyArray {
	
	private long[] array;
	//表示有效数据的长度
	private int elements;
	
	public MyArray() {
		
		array = new long[50];
	}
	
	public MyArray(int maxsize) {
		
		array = new long[maxsize];
	}
	
	/**
	 * 添加数据
	 */
	public void insert(long value) {
		
		array[elements] = value;
		elements++;
	}
	
	/**
	 * 显示数据
	 */
	public void dispaly() {
		
		System.out.print("[ ");
		for (int i = 0; i < elements; i++) {
			System.out.print(array[i] + " ");
		}
		System.out.println("]");
	}
	
	/**
	 * 查找数据
	 */
	public int search(long value) {
		
		int i;
		for (i = 0; i < elements; i++) {
			if(value == array[i]) {
				break;
			}
		}
		if(i == elements) {
			return -1;
		} else {
			return i;
		}
	}
	
	/**
	 * 查找数据，根据索引
	 */
	public long searchByIndex(int index) {
		
		if(index >= elements || index < 0) {
			throw new ArrayIndexOutOfBoundsException();
		} else {
			return array[index];
		}
	}
	
	/**
	 * 删除数据
	 */
	public void delete(int index) {
		
		if(index >= elements || index < 0) {
			throw new ArrayIndexOutOfBoundsException();
		} else {
			for(int i = index; i < elements; i++) {
				array[index] = array[index + 1];
			}
			elements--;
		}
	}
	
	/**
	 * 更新数据
	 */
	public void update(int index, int newValue) {
		
		if(index >= elements || index < 0) {
			throw new ArrayIndexOutOfBoundsException();
		} else {
			array[index] = newValue;
		}
	}
}
